package com.yuntoyun.codeavatar.app.activity.basic;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;

import com.google.gson.JsonObject;

import com.yuntoyun.codeavatar.app.R;
import com.yuntoyun.codeavatar.app.activity.ext.ConstVal;
import com.yuntoyun.codeavatar.app.activity.main.MainActivity;
import com.yuntoyun.codeavatar.app.fwcore.activity.WebPageActivity;
import com.yuntoyun.codeavatar.app.fwcore.core.AppCoreSign;
import com.yuntoyun.codeavatar.app.fwcore.plug.share.mob.PlugMobShare;
import com.yuntoyun.fwcore.appext.data.AppData;
import com.yuntoyun.fwcore.appext.model.UserModel;
import com.yuntoyun.fwcore.base.FwBaseActivity;
import com.yuntoyun.fwcore.model.FwResultJsonDataModel;
import com.yuntoyun.fwcore.model.FwResultJsonListDataModel;
import com.yuntoyun.fwcore.plug.network.retrofit.FwOkHttp;
import com.yuntoyun.fwcore.util.FwAlertDialogUtil;
import com.yuntoyun.fwcore.util.FwComponentUtil;
import com.yuntoyun.fwcore.util.FwGsonUtil;
import com.yuntoyun.fwcore.util.FwIntentUtil;
import com.yuntoyun.fwcore.util.FwLogUtil;
import com.yuntoyun.fwcore.util.FwSoftInputUtil;
import com.yuntoyun.fwcore.util.FwToastUtil;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.OnClick;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.wechat.friends.Wechat;
import io.reactivex.Observable;

public class LoginActivity extends FwBaseActivity {

    private final String fTag = LoginActivity.class.getSimpleName();

    private final int gActionAgreement = 901;
    private final int gActionLogin = 902;
    private final int gActionLoginByWechat = 903;
    private final int gActionBindWechat = 904;

    private final int gRcodeBindPhone = 801;

    @BindView(R.id.ett_account)
    EditText ett_account;
    @BindView(R.id.ett_pwd)
    EditText ett_pwd;
    @BindView(R.id.ivw_agreement)
    ImageView ivw_agreement;

    //登录方式 (1、密码登陆；2、手机短信登陆；3、微信登陆；)
    private int gLoginType = ConstVal.APP_LOGIN_ACCOUNT;
    private int gBindUserId;
    private String gBindToken;

    private String gAgreementUrl;
    private PlugMobShare gPlugMob;
    private boolean gClearAuthData = true;

    @Override
    protected void beforeLayout() {

    }

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_basic_login;
    }

    @Override
    protected void initView() {
        ivw_agreement.setTag(true);
    }

    @Override
    protected void initData() {
        gPlugMob = new PlugMobShare();
    }

    @Override
    protected void initEvent() {

    }

    @Override
    protected void initNavigation() {

    }

    @Override
    protected void messageHandler(Message msg) {

    }

    @Override
    protected void messageHandler(FwResultJsonDataModel model) {
        switch (model.getIndex()) {
            case gActionAgreement:
                gAgreementUrl = fwGsonUtil.getString(model.getFwData(), "userAgreement");
                doAgreement();
                break;
            case gActionLogin:
                doSetLoginInfo(model.getFwData());
                break;
            case gActionLoginByWechat:
                doSetWechatLoginInfo(model.getFwData());
                break;
            case gActionBindWechat:
                this.doCacheSuccessData(model.getFwData());
                break;
        }
    }

    @Override
    protected void messageHandler(FwResultJsonListDataModel model) {

    }

    @OnClick({R.id.ivw_close, R.id.tvw_regist, R.id.btn_login, R.id.tvw_forgetpwd, R.id.llt_agreement, R.id.tvw_agreement, R.id.llt_wechat_login})
    @Override
    public void onClick(View v) {
        if (null == v) return;

        switch (v.getId()) {
            case R.id.ivw_close:
                finish();
                break;
            case R.id.tvw_regist:
                FwIntentUtil.builder().startActivity(this, RegistActivity.class);
                break;
            case R.id.btn_login:
                //账号登录
                gLoginType = ConstVal.APP_LOGIN_ACCOUNT;
                this.doLogin();
                break;
            case R.id.llt_wechat_login:
                //微信登录
                gLoginType = ConstVal.APP_LOGIN_WECHAT;
                this.doLogin();
                break;
            case R.id.tvw_forgetpwd:
                FwIntentUtil.builder().startActivity(this, ForgetPwdActivity.class);
                break;
            case R.id.llt_agreement:
                boolean isAgreed = FwComponentUtil.builder().getViewTag(ivw_agreement);
                ivw_agreement.setTag(!isAgreed);
                ivw_agreement.setImageResource((!isAgreed) ?
                        R.mipmap.icon_action_address_checked :
                        R.mipmap.icon_action_address_unchecked);
                break;
            case R.id.tvw_agreement:
                this.doAgreement();
                break;
            default:
                FwLogUtil.warn(this.fTag, fwActivity.getString(R.string.fw_txt_no_resid));
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        switch (requestCode) {
            case gRcodeBindPhone:
                if (RESULT_OK == resultCode) {
                    gClearAuthData = false;
                    if (null != MainActivity.getInstance()) {
                        //任务界面同步数据
                        MainActivity.getInstance().refreshNavTask();
                        //我的界面同步数据
                        MainActivity.getInstance().refreshNavOwner();
                    }
                    FwToastUtil.builder().makeText("登录成功！请继续操作！");
                    setResult(RESULT_OK);
                    finish();
                } else {
                    //清除登录信息
                    AppData.clearLoginData();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        if (gClearAuthData) {
            AppData.clearLoginData();
        }
        super.onDestroy();
    }

    //++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

    //协议
    private void doAgreement() {
        if (TextUtils.isEmpty(gAgreementUrl)) {
            HashMap<String, Object> map = new HashMap<>();
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getAgreement(map);
            super.doPostData(this.gActionAgreement, observable, true);
        } else {
            Bundle extra = new Bundle();
            extra.putString("ext_title", "用户服务协议");
            extra.putString("ext_url", this.gAgreementUrl);
            FwIntentUtil.builder().startActivity(fwActivity, WebPageActivity.class, extra);
        }
    }

    //执行登录
    private void doLogin() {

        //关闭软键盘
        FwSoftInputUtil.builder().closeKeybord(this);

        boolean isAgreed = FwComponentUtil.builder().getViewTag(ivw_agreement);
        if (!isAgreed) {
            FwToastUtil.builder().makeText("请选择同意协议");
            return;
        }

        if (ConstVal.APP_LOGIN_ACCOUNT == gLoginType) {
            //账号登录
            String valAccount = FwComponentUtil.builder().getViewValue(ett_account);

            if (valAccount.length() != 11) {
                FwToastUtil.builder().makeText("请输入账号");
                return;
            }

            String valPwd = FwComponentUtil.builder().getViewValue(ett_pwd);
            if (valPwd.length() < 1) {
                FwToastUtil.builder().makeText("请输入密码");
                return;
            }

            if (valPwd.length() < 6 || valPwd.length() > 20) {
                FwToastUtil.builder().makeText("请输入6~20位的密码");
                return;
            }

            HashMap<String, Object> map = new HashMap<>();
            map.put("username", valAccount);
            map.put("userpwd", valPwd);
            map.put("action", "account");
            AppCoreSign.addSign(map);
            Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getLogin(map);
            super.doPostData(this.gActionLogin, observable, true);
        } else if (ConstVal.APP_LOGIN_WECHAT == gLoginType) {
            //微信登录（先获取微信信息）
            doGetWechatInfo(0);
        } else {
            FwToastUtil.builder().makeText("没有匹配的登录方式");
        }
    }

    //设置账号或手机号登录数据
    private void doSetLoginInfo(final JsonObject joData) {
        if (joData.has("bindWechat")) {
            boolean bindWechat = FwGsonUtil.builder().getBoolean(joData, "bindWechat");
            if (bindWechat) {
                FwAlertDialogUtil.builder().showCustomConfirmDialog(this, "绑定微信",
                        "绑定微信后，才允许登录！", "暂不绑定", "我要绑定", new FwAlertDialogUtil
                                .CustomClickListener() {


                            @Override
                            public void clickPositiveButton(DialogInterface dialog) {
                                //提交逻辑
                                gBindUserId = fwGsonUtil.getInt(joData, "bindUserId");
                                gBindToken = fwGsonUtil.getString(joData, "bindToken");
                                doGetWechatInfo(1);
                            }

                            @Override
                            public void clickNegativeButton(DialogInterface dialog) {
                                //取消逻辑
                            }
                        });
            } else {
                doCacheSuccessData(joData);
            }
        } else if (joData.has("userToken")) {
            doCacheSuccessData(joData);
        } else {
            FwToastUtil.builder().makeText("服务端响应数据错误！");
        }
    }

    //设置微信登录数据
    private void doSetWechatLoginInfo(final JsonObject joData) {
        if (null == joData) return;

        if (joData.has("has_mobile")) {
            boolean bindPhone = FwGsonUtil.builder().getBoolean(joData, "has_mobile");
            if (!bindPhone) {
                FwAlertDialogUtil.builder().showCustomConfirmDialog(this, "绑定手机号",
                        "绑定手机号后，才允许登录！", "暂不绑定", "我要绑定", new FwAlertDialogUtil
                                .CustomClickListener() {

                            @Override
                            public void clickPositiveButton(DialogInterface dialog) {
                                //提交逻辑
                                if (cacheUserInfo(joData)) {
                                    FwIntentUtil.builder().startActivityForResult(LoginActivity.this, BindPhoneActivity.class, gRcodeBindPhone);
                                } else {
                                    FwToastUtil.builder().makeText("缓存数据失败！");
                                }
                            }

                            @Override
                            public void clickNegativeButton(DialogInterface dialog) {
                                //取消逻辑
                            }
                        });
            } else {
                doCacheSuccessData(joData);
            }
        } else if (joData.has("userToken")) {
            doCacheSuccessData(joData);
        } else {
            FwToastUtil.builder().makeText("服务端响应数据错误！");
        }
    }

    //绑定微信
    private void doBindWechatLogin(HashMap<String, Object> userInfo) {
        String unionid = (String) userInfo.get("unionid");
        String openid = (String) userInfo.get("openid");
        String nickname = (String) userInfo.get("nickname");
        String headimgurl = (String) userInfo.get("headimgurl");
        String Token = (String) userInfo.get("Token");
        //选项：0》保密；1》男；2》女
        int sex = (int) userInfo.get("sex");

        HashMap<String, Object> map = new HashMap<>();
        map.put("bindUserId", gBindUserId);
        map.put("bindToken", gBindToken);
        map.put("wxunionid", unionid);
        map.put("wxopenid", openid);
        map.put("wxnickname", nickname);
        map.put("wxavatar", headimgurl);
        map.put("wxsex", sex);
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().setBindWechat(map);
        super.doPostData(this.gActionBindWechat, observable, true);
    }

    //获取微信授权 (doNextAction:0》登录；1》绑定)
    private void doGetWechatInfo(final int doNextAction) {

        gPlugMob.doThirdLogin(Wechat.NAME, new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                //遍历Map
                FwLogUtil.info(hashMap);//处理后的数据
                FwLogUtil.info(platform.getDb().exportData()); //原始数据

                FwLogUtil.info("doNextAction=" + doNextAction);
                //在主线程中运行
                LoginActivity.this.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        if (0 == doNextAction) {
                            doLoginByWechat(hashMap);
                        } else if (1 == doNextAction) {
                            doBindWechatLogin(hashMap);
                        }
                    }
                });
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                throwable.printStackTrace();
            }

            @Override
            public void onCancel(Platform platform, int i) {
                FwToastUtil.builder().makeText("取消操作");
            }
        });
    }

    //微信登陆
    private void doLoginByWechat(HashMap<String, Object> userInfo) {
        String unionid = (String) userInfo.get("unionid");
        String openid = (String) userInfo.get("openid");
        String nickname = (String) userInfo.get("nickname");
        String headimgurl = (String) userInfo.get("headimgurl");
        String Token = (String) userInfo.get("Token");
        //选项：0》保密；1》男；2》女
        int sex = (int) userInfo.get("sex");

        HashMap<String, Object> map = new HashMap<>();
        map.put("action", "wechat");
//        map.put("fwUserLongitude", "");
//        map.put("fwUserLatitude", "");
        map.put("wxunionid", unionid);
        map.put("wxopenid", openid);
        map.put("wxnickname", nickname);
        map.put("wxavatar", headimgurl);
        map.put("wxsex", sex);
        AppCoreSign.addSign(map);
        Observable<FwResultJsonDataModel> observable = FwOkHttp.getFwAPIService().getLogin(map);
        super.doPostData(this.gActionLoginByWechat, observable, true);
    }


    //缓存数据
    private boolean cacheUserInfo(JsonObject joData) {
        if (null == joData)
            return false;

        UserModel model = new UserModel();
        model.setUserId(fwGsonUtil.getInt(joData, "userId"));
        model.setUserToken(fwGsonUtil.getString(joData, "userToken"));
        model.setCityId(1);
        if (AppData.setPostData(model)) {
            //不清空登录信息
            gClearAuthData = false;
            model.setUserAuth(fwGsonUtil.getInt(joData, "is_partner"));
            return AppData.setUserData(model);
        }
        return false;
    }

    //登录成功
    private void doCacheSuccessData(JsonObject joData) {
        if (null == joData) return;

        if (this.cacheUserInfo(joData)) {
            if (null != MainActivity.getInstance()) {
                //任务界面同步数据
                MainActivity.getInstance().refreshNavTask();
                //我的界面同步数据
                MainActivity.getInstance().refreshNavOwner();
            }

            FwToastUtil.builder().makeText("登录成功！请继续操作！");
            setResult(RESULT_OK);
            finish();
        } else {
            FwToastUtil.builder().makeText("登录失败！无法存储身份标识！");
        }
    }
}
